let dao = require('../database/dao'),
  logger = require('../helper/logger'),
  tagLogger = new logger.TagLogger('VEHICLE_MODEL'),
  errorCode = require('../../conf/errorCode'),
  commonModel = require('./commonModel'),
  util = require('../helper/util'),
  _ = require('lodash');

let {
  genUpdateCallback,
  genInsertCallback,
  genUpdateRslt,
  genUpdateBatchRslt,
  genUpdateBatchCallback,
  genSelectCallback,
  genPagination,
  genInertRslt,
} = commonModel;

//按照capital获取品牌列表
var getVehicleBrandByCapital = (exports.getVehicleBrandByCapital = function(
  capital,
  callback,
) {
  dao.all(
    `select m.id,m.modelName,b.brandLogoUrl,b.brandName from carmodel m 
        left join carbrand b 
            on m.brandId = b.id 
                where b.capital  = ?`,
    [capital],
    genSelectCallback(callback),
  );
});

//getVehicleBrandByCapital('A',(err,_rel)=>{
//console.log(err);
//console.log(_rel);
//});

//按照modelId获取spec列表
var getVehicleSpecByModelId = (exports.getVehicleSpecByModelId = function(
  modelId,
  callback,
) {
  dao.all(
    `select s.id,s.modelId,s.specName name,m.modelImg,s.updateAt,s.specImg from carspec s
        left join carmodel m
            on s.modelId = m.id
      where modelId  = ?`,
    [modelId],
    genSelectCallback(callback),
  );
});

//按照specId获取spec详情
var getVehicleSpecBySpecId = (exports.getVehicleSpecBySpecId = function(
  specId,
  callback,
) {
  dao.all(
    `select 
        s.id,
        s.specName name,
        s.genre,
        s.engine,
        s.marketTime,
        s.manufacturerPrice,
        s.gearBox,
        s.size,
        s.bodyWork,
        s.maxSpeed,
        s.officialAcceleration,
        s.measuredAcceleration,
        s.measuredBraking,
        s.measuredFuelConsumption,
        s.fuelConsumption,
        s.groundClearance,
        s.qualityAssurance,
        s.wheelbase,
        s.frontTrack,
        s.rearTrack,
        s.miniGroundClearance,
        s.allWeight,
        s.tankVolume,
        s.luggageVolume,
        s.engineType,
        s.displacementML,
        s.displacementL,
        s.inlet,
        s.cylinderArrangement,
        s.cylinderNum,
        s.cylinderValves,
        s.reductionRatio,
        s.valveTrain,
        s.bore,
        s.pistonTravel,
        s.maxHorsepower,
        s.maxPower,
        s.maxPowerspeed,
        s.maxTorque,
        s.maxTorquespeed,
        s.engineSpecialtech,
        s.fuelForm,
        s.fuelMark,
        s.fuelSupply,
        s.cylinderHeadmaterial,
        s.cylinderBlockmaterial,
        s.environmentalStandard,
        s.shiftNum,
        s.gearboxType,
        s.drivingMode,
        s.fourwheelDrive,
        s.centralDifferential,
        s.frontSuspension,
        s.rearSuspension,
        s.powerType,
        s.bodyStructure,
        s.frontBrake,
        s.rearBrake,
        s.parkingType,
        s.frontTire,
        s.rearTire,
        s.spareTire,
        s.abs,
        s.brakeDistribution,
        s.brakeAssist,
        s.tractionControl,
        s.stabilityControl,
        s.variableSuspension,
        s.airSuspension,
        s.electroSuspension,
        s.variableSteeringratio,
        s.frontDifferentiallock,
        s.centralDifferentiallock,
        s.rearDifferentiallock,
        s.carId releateCarIds,
        s.specImg,
        m.id modelId,
        m.modelName modelName,
        m.modelImg,
        b.id brandId,
        b.brandName brandName,
        b.brandLogoUrl logoUrl
            from carspec s 
                left join carmodel m on s.modelId = m.id 
                    left join carbrand b on b.id = m.brandId   
                        where s.id = ?`,
    [specId],
    callback,
  );
});

//更新spec详情
exports.updateSpecData = function(specId, data, callback) {
  let str = `UPDATE carspec SET `,
    k = [],
    v = [];
  _.forEach(data, function(value, key) {
    k.push(key + ' = ?');
    v.push(value);
  });
  v.push(specId);
  str = str + k.join(',');
  str = str + ' where id = ?';
  dao.all(str, v, callback);
};

//获取车辆分类
exports.getCarType = function(callback) {
  dao.all(`select * from cartype`, [], callback);
};

//按照modelId获取model详情
var getModelDetailBySpecId = (exports.getModelDetailBySpecId = function(
  modelId,
  callback,
) {
  dao.all(
    `select 
        m.id modelId,
        m.modelName modelName,
        m.modelImg,
        m.released,
        t.id typeId,
        t.name typeName,
        b.id brandId,
        b.brandName brandName,
        b.brandLogoUrl logoUrl
            from carmodel m 
                left join cartype t on m.typeId = t.id 
                    left join carbrand b on b.id = m.brandId   
                        where m.id = ?`,
    [modelId],
    callback,
  );
});

//更新model详情
exports.updateModelDetailByModelId = function(modelId, data, callback) {
  let str = `UPDATE carmodel SET `,
    k = [],
    v = [];
  _.forEach(data, function(value, key) {
    k.push(key + ' = ?');
    v.push(value);
  });
  v.push(modelId);
  str = str + k.join(',');
  str = str + ' where id = ?';
  dao.all(str, v, callback);
};

//增加model
exports.addModel = function(modelObj, callback) {
  dao.insert('carmodel', modelObj, genInsertCallback(callback));
};

//根据前缀，获取品牌列表
exports.getBrandListByNamePrefix = function(namePrefix, callback) {
  let fromJoinWhere = `FROM carbrand where brandName like "${namePrefix}%"`;
  dao.all(
    `SELECT id,brandName ${fromJoinWhere} LIMIT 0,10`,
    [],
    (err, rslts) => {
      if (err == null) callback(null, rslts);
      else callback(err, null);
    },
  );
};
